package com.basker.pisces.springcloud.feign;

import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.util.CollectionUtils;

/**
 * FeignClientFactoryBean注册到BeanFactory后，通过{@link FeignClientBeanProcessor}对所有FeignClientFactoryBean进行后置处理。
 *
 * @author hangwen
 */
public class FeignClientBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    private List<FeignClientBeanProcessor> feignClientBeanProcessors;

    public FeignClientBeanFactoryPostProcessor(List<FeignClientBeanProcessor> feignClientBeanProcessors) {
        this.feignClientBeanProcessors = feignClientBeanProcessors;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        if (CollectionUtils.isEmpty(feignClientBeanProcessors)) {
            return;
        }

        // 获取所有的FeignClientFactoryBean
        String[] feignClientBeanNames = beanFactory.getBeanNamesForAnnotation(FeignClient.class);
        for (String beanName : feignClientBeanNames) {
            Object feignClientFactoryBean = beanFactory.getSingleton(beanName);

            for (FeignClientBeanProcessor processor : feignClientBeanProcessors) {
                processor.processFeignClientBean(feignClientFactoryBean, beanFactory);
            }
        }

    }

}
